import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { api } from '../../api/client';

// 登录参数类型
export interface LoginPayload {
	account: string; // 用户名
	password: string; // 密码
}

// 接口返回用户信息类型
export interface AuthUserInfo {
	username: string;
	role: number;
	userId: number;
	token: string;
}

// Auth 状态
export interface AuthState {
	user: AuthUserInfo | null;
	loading: boolean;
	error: string | null;
}

const initialState: AuthState = {
	user: null,
	loading: false,
	error: null,
};

// 登录异步请求（不包含 UI）
// API: POST http://172.27.2.110/login
export const login = createAsyncThunk<AuthUserInfo, LoginPayload>(
	'auth/login',
	async (payload, { rejectWithValue }) => {
		try {
			const data = await api.post<AuthUserInfo>('http://172.27.2.110/login', payload);
			return data;
		} catch (err: any) {
			return rejectWithValue(err?.message || 'Login failed');
		}
	}
);

// 刷新 Token（无感刷新）
// 约定刷新接口：POST http://172.27.2.110/refresh ，需携带 Authorization: Bearer <oldToken>
// 返回结构与登录一致或至少包含新的 token
export const refreshToken = createAsyncThunk<string>(
	'auth/refreshToken',
	async (_, { getState, rejectWithValue }) => {
		try {
			const state = getState() as { auth: AuthState };
			const token = state.auth.user?.token;
			if (!token) throw new Error('No token');
			const res = await fetch('http://172.27.2.110/refresh', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`,
				},
				body: JSON.stringify({}),
			});
			if (!res.ok) {
				const text = await res.text();
				throw new Error(text || `HTTP ${res.status}`);
			}
			// 兼容两种返回：仅 token 或完整用户
			const data = (await res.json()) as Partial<AuthUserInfo> & { token?: string };
			const newToken = data.token;
			if (!newToken) throw new Error('No token in refresh response');
			return newToken;
		} catch (err: any) {
			return rejectWithValue(err?.message || 'Refresh failed');
		}
	}
);

const authSlice = createSlice({
	name: 'auth',
	initialState,
	reducers: {
		logout(state) {
			state.user = null;
			state.error = null;
		},
	},
	extraReducers: (builder) => {
		builder
			.addCase(login.pending, (state) => {
				state.loading = true;
				state.error = null;
			})
			.addCase(login.fulfilled, (state, action) => {
				state.loading = false;
				state.user = action.payload;
			})
			.addCase(login.rejected, (state, action) => {
				state.loading = false;
				state.error = (action.payload as string) || 'Login failed';
			})
			// 刷新成功：仅更新 token
			.addCase(refreshToken.fulfilled, (state, action) => {
				if (state.user) {
					state.user.token = action.payload;
				}
			})
			// 刷新失败：不在此处登出，由调用方决定（全局 client 会登出并跳转）
			.addCase(refreshToken.rejected, (state, action) => {
				state.error = (action.payload as string) || 'Refresh failed';
			});
	},
});

export const { logout } = authSlice.actions;
export default authSlice.reducer;
